/**
 * localstorage 存储类
 * by feifei
 */
export default {
    /**
     *
     * @param {*} key 键
     * @returns
     */
    get: function (key) {
        const storage = window.localStorage;
        const cacheString = storage.getItem(key);
        if (cacheString) {
            const cacheObj = JSON.parse(cacheString);
            if (cacheObj.expire < 0) {
                return cacheObj.val;
            } else {
                const now = Math.round(new Date().getTime() / 1000);
                if (now < cacheObj.expire) {
                    return cacheObj.val;
                } else {
                    storage.removeItem(key);
                    return undefined;
                }
            }
        } else {
            return undefined;
        }
    },
    /**
     * 存储数据
     * @param {*} key 键
     * @param {*} value 值
     * @param {*} expire 键值有效期 单位秒 ，-1 永不过期
     */
    set: function (key, value, expire = -1) {
        const storage = window.localStorage;
        let cacheObj = null;
        // 缓存
        if (expire >= 0) {
            const now = Math.round(new Date().getTime() / 1000);
            //算出过期时间
            expire = now + expire;
            cacheObj = { expire, val: value };
        } else {
            cacheObj = { expire: -1, val: value };
        }
        storage.setItem(key, JSON.stringify(cacheObj));
    },
    /**
     * 获取键过期时间 -1 永不过期  0 已过期
     * @param {*} key 键
     * @returns
     */
    ttl: function (key) {
        const storage = window.localStorage;
        const cacheString = storage.getItem(key);

        if (cacheString) {
            const cacheObj = JSON.parse(cacheString);
            if (cacheObj.expire < 0) {
                return -1;
            } else {
                const now = Math.round(new Date().getTime() / 1000);
                const left = cacheObj.expire - now;
                if (left <= 0) {
                    return 0;
                }
                return left;
            }
        } else {
            return 0;
        }
    },
    /**
     * 判断键是否存在
     * @param {*} key 键
     * @returns
     */
    has: function (key) {
        const key_ttl = this.ttl(key);
        if (key_ttl == -1 || key_ttl > 0) {
            return true;
        } else {
            return false;
        }
    },
    remove: function (key) {
        const storage = window.localStorage;
        storage.removeItem(key);
    }
};
